package com.ubi.core.utils.converter;

import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.util.Date;

public class DateConverter implements Converter<Date> {

    public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static final String DATE_FORMAT_WITHOUT_HOURS = "yyyy-MM-dd";

    @Override
    public Date convert(String dateStr) {
        try {
            String format = getProperlyDateFormat(dateStr);
            return DateUtils.parseDate(dateStr, format);
        } catch (ParseException e) {
            throw new IllegalStateException("不合法的日期格式:" + dateStr);
        }
    }

    String getProperlyDateFormat(String dateStr) {
        if (dateStr.contains(":")) {
            return DATE_FORMAT;
        }
        return DATE_FORMAT_WITHOUT_HOURS;
    }
}
